import cv2
import numpy as np

def get_target_hole_position_no_display(image_path, output_image_path="result.png"):
    """
    计算图片中目标缺口位置，并保存处理后的图片，不进行实时显示。
    """
    img = cv2.imread(image_path)
    if img is None:
        print(f"错误: 无法加载图片 '{image_path}'")
        return None

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 100, 200)
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    potential_holes_x = []
    for contour in contours:
        area = cv2.contourArea(contour)
        # print(f"面积:{area}")
        if 10000 < area < 20000:
            M = cv2.moments(contour)
            if M["m00"] != 0:
                cx = int(M["m10"] / M["m00"])
                potential_holes_x.append(cx)

    return max(potential_holes_x)

# --- 使用示例 ---
if __name__ == "__main__":
    image_file = f'outimg2.jpg'
    output_file = f'handle.png' # 指定输出文件名
    x = get_target_hole_position_no_display(image_file, output_file)
    print(f"目标缺口位置: {x}")
        